<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新增</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <tree-table :data="treeList" border>
          <el-table-column label="产品名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.pname }}
            </template>
          </el-table-column>
          <el-table-column label="基准价格" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.pprice }}
            </template>
          </el-table-column>
          <el-table-column label="化妆说明" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.desc1 }}
            </template>
          </el-table-column>
          <el-table-column label="服装说明" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.desc2 }}
            </template>
          </el-table-column>
          <el-table-column label="修图说明" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.desc3 }}
            </template>
          </el-table-column>
          <el-table-column label="冲印说明" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.desc4 }}
            </template>
          </el-table-column>
          <el-table-column label="拍摄说明" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.desc5 }}
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="有效标志" style="width: 10%" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300" fixed="right" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
              <template v-if="!scope.row.children || scope.row.children.length <= 0 ">
                <el-button size="mini" type="primary" @click="addAttrList(scope.row)">
                  销售属性
                </el-button>
              </template>
            </template>
          </el-table-column>
        </tree-table>

      </el-col>
    </el-row>

    <!-- 商品编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="70%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" label-width="120px" prop="pname">
              <el-input v-model="temp.pname"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父级产品" label-width="120px" prop="parentId">
              <el-select v-model="temp.parentId" class="filter-item" placeholder="请选择父级产品">
                <el-option v-for="item in rootData" :key="item.pid" :label="item.pname" :value="item.pid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基准价格" label-width="120px" prop="pprice">
              <el-input v-model.number="temp.pprice"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效标志" label-width="120px">
              <el-switch
                v-model="validSwitch"
                active-color="#13ce66"
                inactive-color="#ff4949"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大拍摄人数" label-width="120px" prop="maxNum">
              <el-input v-model.number="temp.maxNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小拍摄人数" label-width="120px" prop="minNum">
              <el-input v-model.number="temp.minNum"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="每加一人的价格" label-width="120px" prop="personPrice">
              <el-input v-model.number="temp.personPrice"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="同类型多套优惠" label-width="120px" prop="cheapMoney">
              <el-input v-model.number="temp.cheapMoney"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" label-width="120px" prop="personPrice">
              <el-input v-model.number="temp.sort"/>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="editable">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="化妆说明" label-width="120px" prop="desc1">
                <el-input v-model="temp.desc1" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服装说明" label-width="120px" prop="desc2">
                <el-input v-model="temp.desc2"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="拍摄说明" label-width="120px" prop="desc3">
                <el-input v-model="temp.desc3" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="修图说明" label-width="120px" prop="desc4">
                <el-input v-model="temp.desc4" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="冲印说明" label-width="120px" prop="desc5">
                <el-input v-model="temp.desc5" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属首页类别" label-width="120px" prop="parentId">
                <el-select v-model="temp.sxIndexCategories" multiple value-key="categoryId" class="filter-item" placeholder="请选择展示类别">
                  <el-option v-for="item in sxCategories" :key="item.categoryId" :label="item.categoryName" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="首页图片" label-width="120px" prop="pindexImg">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :action="uploadUrl"
                  class="avatar-uploader">
                  <img v-if="temp.pindexImg" :src="temp.pindexImg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <span>高度为350，宽度不限</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详情图片" label-width="120px" prop="pmoreImg">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess1"
                  :before-upload="beforeAvatarUpload"
                  :action="uploadUrl"
                  class="avatar-uploader">
                  <img v-if="temp.pmoreImg" :src="temp.pmoreImg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <span>格式为670x670</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="猜你喜欢" label-width="120px" prop="pindexImg">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess2"
                  :before-upload="beforeAvatarUpload"
                  :action="uploadUrl"
                  class="avatar-uploader">
                  <img v-if="temp.plikeImg" :src="temp.plikeImg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <span>高度为350，宽度350</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否多选" label-width="120px" prop="isMulti">
                <el-switch
                  v-model="validIsMulti"
                  active-color="#13ce66"
                  inactive-color="#ff4949"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="说明标题" label-width="120px" prop="productTitle">
                <el-input v-model="temp.productTitle" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="说明内容" label-width="120px" prop="productDesc">
                <tinymce :custom-modal="editModal" :upload-url="uploadUrl" :height="300" v-model="temp.productDesc" :reset="!dialogFormVisible"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="展示内容" label-width="120px" prop="desc6">
                <tinymce :custom-modal="editModal" :upload-url="uploadUrl" :height="300" v-model="temp.desc6" :reset="!dialogFormVisible"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="服务体验内容" label-width="120px" prop="desc7">
                <tinymce :custom-modal="editModal" :upload-url="uploadUrl" :height="300" v-model="temp.desc7" :reset="!dialogFormVisible"/>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sxProductBasicInfoApi from '@/api/manage/SxProductBasicInfoApi'
import sxIndexCategoryApi from '@/api/manage/SxIndexCategoryApi'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import treeTable from '@/components/TreeTable'
import { buildTreeData } from '@/utils/TreeUtil'

export default {
  directives: { waves },
  components: { Pagination, Tinymce, treeTable },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        0: 'danger'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '有效',
        0: '作废'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      tableKey: 0, // 表格key值
      list: null, // 表格对象
      rootData: [], // 顶级结点
      sxCategories: [], // 类别数组
      listLoading: true, // 表格加载框
      total: 0, // 分页总数
      tableHeight: window.innerHeight - 220, // 表格高度
      temp: {
        pid: '',
        pname: '',
        pindexImg: '',
        pmoreImg: '',
        pprice: 0,
        desc1: '',
        desc2: '',
        desc3: '',
        desc4: '',
        desc5: '',
        desc6: '',
        desc7: '',
        parentId: '',
        maxNum: 1,
        minNum: 1,
        sort: 0,
        personPrice: 0,
        cheapMoney: 0,
        productTitle: '',
        productDesc: '',
        isMulti: false,
        createdTime: '',
        modifiedTime: '',
        validFlag: '1',
        plikeImg: '',
        sxIndexCategories: []
      }, // 编辑框临时变量
      statusOptions: { // 有效无效下拉框
        '1': '有效',
        '0': '作废'
      },
      editable: true,
      dialogFormVisible: false, // 编辑框显示
      dialogAttrVisible: false, // 属性框显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      uploadUrl: process.env.BASE_API + '/file/upload',
      rules: {
        // 编辑框校验规则
        sxProductBasicInfoName: [{ required: true, message: '产品基本信息名称', trigger: 'change' }],
        parentId: [{ required: true, message: '父节点不能为空', trigger: 'change' }],
        pindexImg: [{ required: true, message: '首页图片不能为空', trigger: 'change' }],
        plikeImg: [{ required: true, message: '类别不能为空', trigger: 'change' }],
        maxNum: [{ type: 'number', message: '最大人数必须为数字' }],
        minNum: [{ type: 'number', message: '最小人数必须为数字' }],
        pprice: [{ type: 'number', message: '必须为数字' }],
        personPrice: [{ type: 'number', message: '必须为数字' }],
        cheapMoney: [{ type: 'number', message: '必须为数字' }],

      },
      editModal: false
    }
  },
  computed: {
    validIsMulti: {
      // getter
      get: function() {
        return this.temp.isMulti
      },
      // setter
      set: function(newValue) {
        this.temp.isMulti = newValue
      }
    },
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    },
    parentId() {
      return this.temp.parentId
    },
    treeList() {
      return buildTreeData(this.list, { id: 'pid', pid: 'parentId' })
    }
  },
  watch: {
    parentId(newValue, oldValue) {
      if (newValue === '##' || newValue === '') {
        this.editable = true
      } else {
        this.editable = false
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {

    addAttrList(row) {
      this.$router.push({ name: 'itemConfigManage', params: row })
    },

    /**
     * 获取顶级结点
     * */
    getRootData() {
      sxProductBasicInfoApi.getRootData({ r: Math.random() }).then((data) => {
        this.rootData = [{ 'pid': '##', 'pname': '顶级节点' }].concat(data)
      })
    },

    /**
     *  获取类别数组
     * */
    getCategoriesData() {
      sxIndexCategoryApi.getList({}).then(data => {
        this.sxCategories = data
      })
    },

    /**
       * 获取表格数据
       */
    fetchData() {
      this.listLoading = true
      sxProductBasicInfoApi.getList({}).then(data => {
        this.list = data
        this.listLoading = false
      })
    },

    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.getRootData()
      this.getCategoriesData()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        pid: '',
        pname: '',
        pindexImg: '',
        pmoreImg: '',
        pprice: 0,
        desc1: '',
        desc2: '',
        desc3: '',
        desc4: '',
        desc5: '',
        desc6: '',
        desc7: '',
        sort: 0,
        parentId: '',
        maxNum: 1,
        minNum: 1,
        personPrice: 0,
        cheapMoney: 0,
        createdTime: '',
        modifiedTime: '',
        validFlag: '1',
        plikeImg: '',
        sxIndexCategories: []
      }
    },
    /**
       * 确定新增
       */
    createData() {
      const that = this
      debugger
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          sxProductBasicInfoApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      sxProductBasicInfoApi.get(row).then(data => {
        this.temp = data
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.getRootData()
        this.getCategoriesData()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          sxProductBasicInfoApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      if (row.children && row.children.length > 0) {
        this.$message({
          type: 'info',
          message: '请先删除子商品'
        })
      } else {
        this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sxProductBasicInfoApi.remove({ pid: row.pid }).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },

    handleAvatarSuccess(res, file) {
      this.temp.pindexImg = res.data[0]
    },
    handleAvatarSuccess1(res, file) {
      this.temp.pmoreImg = res.data[0]
    },
    handleAvatarSuccess2(res, file) {
      this.temp.plikeImg = res.data[0]
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
